package project.base.common.config

import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.jdbc.DataSourceBuilder
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import project.base.common.constant.DataSourceConstant
import project.base.common.database.DynamicDataSource
import javax.sql.DataSource

/**
 * 动态数据源配置
 * @author: 三味
 * @update: 2022/3/2 20:14
 */
@Configuration
@EnableAutoConfiguration(exclude = [DataSourceAutoConfiguration::class])
open class DynamicDataSourceConfig {

    @Bean(DataSourceConstant.MASTER)
    @ConfigurationProperties(prefix = "spring.datasource.master")
    open fun masterDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Bean(DataSourceConstant.SLAVE)
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    open fun slaveDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Bean
    @Primary
    open fun dynamicDataSource(): DataSource? {
        val dataSourceMap: MutableMap<Any, Any> = HashMap(2)
        dataSourceMap[DataSourceConstant.SLAVE] = slaveDataSource()
        dataSourceMap[DataSourceConstant.MASTER] = masterDataSource()
        //设置动态数据源
        val dynamicDataSource = DynamicDataSource()
        dynamicDataSource.setTargetDataSources(dataSourceMap)
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource())
        return dynamicDataSource
    }
}
